package com.exchange.plugin.influx;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.influxdb.dto.Point;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;
import org.influxdb.impl.InfluxDBResultMapper;
import com.jfinal.kit.PropKit;

public class InfluxDbKit {
	static InfluxDBResultMapper resultMapper = new InfluxDBResultMapper(); // thread-safe - can be reused
	
	/**
	 * 创建自定义保留策略
	 * 
	 * @param policyName   策略名
	 * @param duration  保存天数
	 * @param replication 保存副本数量
	 * @param isDefault 是否设为默认保留策略
	 */
	public static void createRetentionPolicy(String policyName, String duration, int replication, Boolean isDefault) {
		InFluxDbPlugin.influxDB.createRetentionPolicy(policyName, PropKit.get("influxDbDatabase"), duration, replication, isDefault);
	}
	
	/**
	 * 插入一行数据
	 */
	public static void insertValue(String code, BigDecimal open, BigDecimal high, BigDecimal low, BigDecimal close, BigDecimal vol) {
        Point point = Point.measurement(code)//表名
                .tag("code", code)//如：BTCUSDT
                .addField("open", open).addField("high", high).addField("low", low).addField("close", close).addField("vol", vol)
                .build();
        InFluxDbPlugin.influxDB.write(PropKit.get("influxDbDatabase"), "autogen",point);//autogen自动生成的永久保留数据的策略
    }
	
	/**
	 * 通过时间查询（只是用来查历史记录）1576018620000000000
	 */
	public static List<KlinesData> queryKline(String code, Long start, Long end, String sample, int limit) {
        String queryStr = String.format("select FIRST(open),MAX(high),MIN(low),LAST(close),SUM(vol),COUNT(open) from %s where time >= %d and time <= %d GROUP BY time(%s) order by time desc limit %d", code, start,end, sample, limit); 
        Query query = new Query(queryStr, PropKit.get("influxDbDatabase"));
        QueryResult result = InFluxDbPlugin.influxDB.query(query);
        return resultMapper.toPOJO(result, KlinesData.class, code);
    }
	
	/**
     * 当前价格
     */
    public static BigDecimal getMarketPrice(String code){
    	BigDecimal price = BigDecimal.ZERO;
        String queryStr = String.format("select close from %s order by time desc limit 1",code);
        Query query = new Query(queryStr, PropKit.get("influxDbDatabase"));
        QueryResult result = InFluxDbPlugin.influxDB.query(query);
        List<PriceData> marketPrice = resultMapper.toPOJO(result, PriceData.class, code);
        if (marketPrice.size() > 0) {
        	price = new BigDecimal(marketPrice.get(0).getClose());
        }
        return price;
    }
    
    /**
     * 昨日价格收盘
     */
    public static BigDecimal getYesterdayPrice(String code){
    	BigDecimal price = BigDecimal.ZERO;
        String queryStr = String.format("select last(close) from %s where time > now() - 1d group by time(1d) order by time asc limit 1",code);
        Query query = new Query(queryStr, PropKit.get("influxDbDatabase"));
        QueryResult result = InFluxDbPlugin.influxDB.query(query);
        List<PriceData> marketPrice = resultMapper.toPOJO(result, PriceData.class, code);
        if (marketPrice.size() > 0) {
        	price = new BigDecimal(marketPrice.get(0).getLast());
        }
        return price;
    }
    
    /**
     * 24小时的交易量
     */
    public static BigDecimal getVol24H(String code) {
    	BigDecimal price = BigDecimal.ZERO;
        String queryStr = String.format(" select sum(vol) from %s where time > now() - 1d group by time(1d) order by time desc limit 1",code);
        Query query = new Query(queryStr, PropKit.get("influxDbDatabase"));
        QueryResult result = InFluxDbPlugin.influxDB.query(query);
        List<PriceData> marketPrice = resultMapper.toPOJO(result, PriceData.class, code);
        if (marketPrice.size() > 0) {
        	price = new BigDecimal(marketPrice.get(0).getSum());
        }
        return price;
    }
    
    public static void main(String[] args) {
    	InfluxDB influxDB = InfluxDBFactory.connect("http://192.168.0.200:8086", "notHave", "notHave");
    	Point point = Point.measurement("kline_new")//表名
//                .time(time, TimeUnit.MILLISECONDS)
                .tag("code", "my")//如：BTCUSDT
                .addField("open", 4).addField("high", 4).addField("low", 4).addField("close", 4).addField("vol", 1)
                .build();
    	influxDB.write("klines_test", "autogen",point);
        

//        service.getInstance().query(query);
//        List<KLinesVo> eos_usdt = service.queryKline("BTC/USDT", 0l, System.currentTimeMillis(), "15m", 200);
//        eos_usdt.clear();;


    }
	
}
